package com.yuncheng.spcyApi.spcy;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.bo.ParamsBo;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.mapper.SpcyFgbzkBasicMapper;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.spcyService.FgbzkBusService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.HttpResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.vo.common.PageVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
import utils.*;

@Api(tags = "审评查验-法律标准库接口")
@RestController
@RequestMapping("/api/spzx-spcy/fgbzk")
public class SpcyFgbzkController {

    private static final Logger log = LoggerFactory.getLogger(SpcyFgbzkController.class);

    @Resource
    private ISpcyFgbzkBasicService spcyFgbzkBasicService;

    @Resource
    private SpcyFgbzkBasicMapper spcyFgbzkBasicMapper;

    @Resource
    private ISpcyFgbzkTypeService spcyFgbzkTypeService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private FgbzkBusService fgbzkBusService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Log(title = "法规标准库-资源库-分页列表查询")
    @ApiOperation(value = "法规标准库-资源库-分页列表查询")
    @GetMapping(value = "/queryPageList")
    public HttpResult<?> queryPageList(SpcyFgbzkBasic bean, PageVo pageVo) {
        Page<SpcyFgbzkBasic> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());

        if (StringUtils.isNotBlank(bean.getFtypeid())){
            bean.setFtype(null);
        }

        if (StringUtils.isBlank(bean.getFzt())) {
            bean.setFzt(SpcyConstant.Zltxwj_Zt_Yx);
        }
        IPage<SpcyFgbzkBasic> pageList = spcyFgbzkBasicMapper.selectPageList(page, bean);
        return HttpResult.ok(pageList);
    }


    @Log(title = "法规标准库-资源库-添加")
    @ApiOperation(value = "法规标准库-资源库-添加")
    @PostMapping(value = "/addZltxwj")
    public HttpResult addZltxwj(@RequestBody SpcyFgbzkBasic spcyFgbzkBasic) {
        if (StringUtils.isBlank(spcyFgbzkBasic.getFwjmc())){
            return HttpResult.error("文件名称不能为空");
        }

        if (StringUtils.isBlank(spcyFgbzkBasic.getId())) {
            List<SpcyFgbzkBasic> xydmList = spcyFgbzkBasicService.list(new LambdaQueryWrapper<SpcyFgbzkBasic>()
                    .eq(SpcyFgbzkBasic::getFwjmc, spcyFgbzkBasic.getFwjmc()));
            // 判断法规标准库是否存在
            if (CollectionUtils.isNotEmpty(xydmList)) {
                return HttpResult.error("文件名称，已经存在了。");
            }
            spcyFgbzkBasic.setId(GetUuIdUtils.ReplaceUuId());
            if (spcyFgbzkBasic.getFscrq() == null){
                spcyFgbzkBasic.setFscrq(new Date());
            }
            if (spcyFgbzkBasic.getFssrq() == null){
                spcyFgbzkBasic.setFssrq(new Date());
            }

            // 排序
            int total = Optional.ofNullable(spcyFgbzkBasicService.getZltxwjBasicTotal()).orElseGet(()->0);
            int order = total + 1;
            spcyFgbzkBasic.setForder(order);

            if (StringUtils.isBlank(spcyFgbzkBasic.getFzt())) {
                spcyFgbzkBasic.setFzt(SpcyConstant.Zltxwj_Zt_Yx); // 默认：现行有效
            }

            if (StringUtils.isNotBlank(spcyFgbzkBasic.getFtypeid())){
                SpcyFgbzkType type = spcyFgbzkTypeService.getById(spcyFgbzkBasic.getFtypeid());
                if (type != null){
                    spcyFgbzkBasic.setFtype(type.getFlxmc());
                }
            }else {
                if (StringUtils.isBlank(spcyFgbzkBasic.getFtype())){
                    return HttpResult.error("分类不能为空");
                }
            }

            boolean save = spcyFgbzkBasicService.save(spcyFgbzkBasic);
            if (save) {
                String operContent = "新增法规标准库信息：";

                // 将map里面的属性和值转String
                Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcyFgbzkBasic);
                operContent += LogUtils.MapToStringMethod(beanMap);
                spcyLogService.addLogs(LogConstant.LOGS_FGBZK, operContent, spcyFgbzkBasic.getId(), SpcyConstant.LOGS_SYS_TYPE_XZ, SpcyConstant.LOGS_SYS_TYPE_XZ);
            }
        }else {
            SpcyFgbzkBasic zltxwjUpdate = spcyFgbzkBasicService.getById(spcyFgbzkBasic.getId());
            if (zltxwjUpdate == null){
                return HttpResult.error("当前法规标准库不存在。");
            }

            ConvertUtils.register(new DateConvert(), java.util.Date.class);
            // 自动完成页面到bean的数据对接
            try {
                BeanUtils.populate(zltxwjUpdate, BeanUtils.describe(spcyFgbzkBasic));
                zltxwjUpdate.setFssrq(spcyFgbzkBasic.getFssrq());

                if (StringUtils.isNotBlank(zltxwjUpdate.getFtypeid())){
                    SpcyFgbzkType type = spcyFgbzkTypeService.getById(zltxwjUpdate.getFtypeid());
                    if (type != null){
                        zltxwjUpdate.setFtype(type.getFlxmc());
                    }
                }

            } catch (IllegalAccessException e) {
                log.error("法规标准库-资源库-更新失败[IllegalAccessException]: {}",e.getMessage());
            } catch (InvocationTargetException e) {
                log.error("法规标准库-资源库-更新失败[InvocationTargetException]: {}",e.getMessage());
            } catch (NoSuchMethodException e) {
                log.error("法规标准库-资源库-更新失败[]: {NoSuchMethodException}",e.getMessage());
            }

            boolean flag = spcyFgbzkBasicService.updateById(zltxwjUpdate);
            if (flag) {
                String operContent = "基本信息修改：";
                Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(zltxwjUpdate);
                operContent += LogUtils.BeanModifyMsg(zltxwjUpdate, oldMap);

                spcyLogService.addLogs(LogConstant.LOGS_FGBZK, operContent, spcyFgbzkBasic.getId(), SpcyConstant.LOGS_SYS_TYPE_XG, SpcyConstant.LOGS_SYS_TYPE_XG);
            }
        }

        HttpResult<String> result = new HttpResult(true);
        result.setResult(spcyFgbzkBasic.getId());
        result.setMessage("保存成功");
        return result;
    }

    @Log(title = "法规标准库-资源库-编辑")
    @ApiOperation(value = "法规标准库-资源库-编辑")
    @PutMapping(value = "/editZltxwj")
    public HttpResult<?> editZltxwj(@RequestBody SpcyFgbzkBasic spcyFgbzkBasic) {
        if (StringUtils.isBlank(spcyFgbzkBasic.getId())){
            return HttpResult.error("体系文件主要参数丢失，请联系管理员");
        }
        SpcyFgbzkBasic zltxwjUpdate = spcyFgbzkBasicService.getById(spcyFgbzkBasic.getId());
        if (zltxwjUpdate == null){
            return HttpResult.error("当前法规标准库不存在。");
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(zltxwjUpdate);
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        try {
            BeanUtils.populate(zltxwjUpdate, BeanUtils.describe(spcyFgbzkBasic));
            zltxwjUpdate.setFssrq(spcyFgbzkBasic.getFssrq());

            if (StringUtils.isNotBlank(zltxwjUpdate.getFtypeid())){
                SpcyFgbzkType type = spcyFgbzkTypeService.getById(zltxwjUpdate.getFtypeid());
                if (type != null){
                    zltxwjUpdate.setFtype(type.getFlxmc());
                }
            }
        } catch (IllegalAccessException e) {
            log.error("法规标准库-资源库-更新失败[IllegalAccessException]: {}",e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("法规标准库-资源库-更新失败[InvocationTargetException]: {}",e.getMessage());
        } catch (NoSuchMethodException e) {
            log.error("法规标准库-资源库-更新失败[]: {NoSuchMethodException}",e.getMessage());
        }
        boolean flag = spcyFgbzkBasicService.updateById(zltxwjUpdate);
        if (flag) {
            String operContent = "基本信息修改：";
            operContent += LogUtils.BeanModifyMsg(zltxwjUpdate, oldMap);

            spcyLogService.addLogs(LogConstant.LOGS_FGBZK, operContent, spcyFgbzkBasic.getId(), SpcyConstant.LOGS_SYS_TYPE_XG, SpcyConstant.LOGS_SYS_TYPE_XG);
        }

        return HttpResult.ok("保存成功");
    }

    @Log(title = "法规标准库-资源库-批量删除")
    @ApiOperation(value = "法规标准库-资源库-批量删除")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "法规标准库id,多个参数用[英文逗号]拼接")
    })
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyFgbzkBasic> zltxwjList = spcyFgbzkBasicService.listByIds(idsList);
        if (CollectionUtils.isEmpty(zltxwjList)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcyFgbzkBasic zltxwj : zltxwjList){
            spcyFgbzkBasicService.removeById(zltxwj.getId());

            if (StringUtils.isNotBlank(zltxwj.getFwjlj())){
                localFileUploadUtils.deleteLocalFileUrlByZdy(zltxwj.getFwjlj());
            }
            if (StringUtils.isNotBlank(zltxwj.getFpdfurl())){
                localFileUploadUtils.deleteLocalFileUrlByZdy(zltxwj.getFpdfurl());
            }

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(zltxwj);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_FGBZK,operContent,zltxwj.getId(),SpcyConstant.LOGS_SYS_TYPE_SC,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    @Log(title = "法规标准库-资源库-通过id查询")
    @ApiOperation(value = "法规标准库-资源库-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyFgbzkBasic SpcyFgbzkBasic = spcyFgbzkBasicService.getById(id);
        return HttpResult.ok(SpcyFgbzkBasic);
    }

    @Log(title = "法规标准库-上传文件")
    @ApiOperation(value = "法规标准库-上传文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "文件不能为空",required = true),
            @ApiImplicitParam(name = "id",value = "法规标准库id",required = true)
    })
    @PostMapping(value = "/uploadZltxwjFile")
    public HttpResult<?> uploadZltxwjFile(@RequestPart("file") MultipartFile file,
                                          @RequestParam(value = "id",defaultValue = "") String id){

        if (StringUtils.isEmpty(id)){
            return HttpResult.error("法规标准库参数不能为空");
        }
        SpcyFgbzkBasic zltxwj = spcyFgbzkBasicService.getById(id);
        if (zltxwj == null){
            return HttpResult.error("当前法规标准库记录不存在，请刷新重试");
        }
        if (StringUtils.isBlank(zltxwj.getFwjmc())){
            return HttpResult.error("请先输入文件名");
        }
        if (StringUtils.isBlank(zltxwj.getFtype())){
            return HttpResult.error("请先选中分类");
        }

        String typeUrl = zltxwj.getFtype(); // 分类路径

        /**
         * 如果旧的文件存在，将旧的文件移动到新的文件目录
         */
        String oldCflj = zltxwj.getFwjlj(); // 旧的文件路径
        if (StringUtils.isNotBlank(oldCflj)){
            localFileUploadUtils.deleteLocalFileUrlByZltxwj(oldCflj);
        }

        String originalFilename = file.getOriginalFilename();
        // 文件类型
        String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));

        String wjccmc = zltxwj.getFwjmc() + wjlx;
        String ml = SpcyConstant.FGBZK_File_Base_Url + "/" + typeUrl;

        localFileUploadUtils.uploadFgbzkFile(file, wjccmc, ml); // 上传文件

        zltxwj.setFwjlx(wjlx);
        String cflj = "/" + ml + "/" + wjccmc;
        zltxwj.setFwjlj(cflj);
        boolean flag = spcyFgbzkBasicService.updateById(zltxwj);
        if (flag) {
            String czContent = "上传法规标准库: ";
            Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(zltxwj);
            czContent += LogUtils.MapToStringMethod(wjjlMap);
            spcyLogService.addLogs(LogConstant.LOGS_FGBZK, czContent, id, SpcyConstant.LOGS_SYS_TYPE_BC, SpcyConstant.LOGS_SYS_TYPE_BC);
        }

        return HttpResult.ok("上传成功");
    }

    @Log(title = "法规标准库-下载文件")
    @ApiOperation(value = "法规标准库-下载文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "法规标准库id",required = true)
    })
    @GetMapping(value = "/getZltxwjFile")
    public void getZltxwjFile(@RequestParam(value = "id",defaultValue = "") String fileId, HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)){
            throw new BusinessException("法规标准库参数为空");
        }

        SpcyFgbzkBasic zltxwj = spcyFgbzkBasicService.getById(fileId);
        if (zltxwj == null){
            throw new BusinessException("法规标准库id为-{}的文件记录不存在"+fileId);
        }
        localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj.getFwjlj(),response);
    }

    @Log(title = "法规标准库-下载pdf版文件")
    @ApiOperation(value = "法规标准库-下载pdf版文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "法规标准库id",required = true)
    })
    @GetMapping(value = "/getZltxwjPdfFile")
    public void getZltxwjPdfFile(@RequestParam(value = "id",defaultValue = "") String fileId, HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)){
            log.error("法规标准库id为空");
            return;
        }

        SpcyFgbzkBasic zltxwj = spcyFgbzkBasicService.getById(fileId);
        if (zltxwj == null){
            log.error("法规标准库id为-{}的文件记录不存在",fileId);
            throw new BusinessException("法规标准库id为-{}的文件记录不存在"+fileId);
        }
        if (StringUtils.isBlank(zltxwj.getFpdfurl())){
            if (StringUtils.isNotBlank(zltxwj.getFwjlj())){
                SpcyFgbzkBasic zltxwj2 = fgbzkBusService.zltxwjToPdf(zltxwj, false);

                if (zltxwj2 != null && StringUtils.isNotBlank(zltxwj2.getFpdfurl())) {
                    localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj2.getFpdfurl(), response);
                }else {
                    throw new BusinessException("下载失败！");
                }
            }else {
                throw new BusinessException("法规标准库id为-{}的文件不存在"+fileId);
            }
        }else {
            localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj.getFpdfurl(), response);
        }
    }

    @Log(title = "法规标准库-删除文件")
    @ApiOperation(value = "法规标准库-删除文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "法规标准库id",dataType = "String",required = true),
    })
    @DeleteMapping(value = "/deleteZltxwjFileById")
    public HttpResult<?> deleteZltxwjFileById(@RequestParam("id")String fileId){
        if (StringUtils.isEmpty(fileId)){
            return HttpResult.error("文件记录id不能为空");
        }

        SpcyFgbzkBasic zltxwj = spcyFgbzkBasicService.getById(fileId);
        if (zltxwj == null){
            return HttpResult.error("文件记录不存在");
        }
        if (StringUtils.isNotBlank(zltxwj.getFwjlj())) {
            localFileUploadUtils.deleteLocalFileUrlByZltxwj(zltxwj.getFwjlj());
            if (StringUtils.isNotBlank(zltxwj.getFpdfurl())){
                localFileUploadUtils.deleteLocalFileUrlByZltxwj(zltxwj.getFpdfurl());
            }
            zltxwj.setFwjlj("");
            zltxwj.setFwjlx("");
            zltxwj.setFpdfurl("");
            spcyFgbzkBasicService.updateById(zltxwj);

            String czContent = "删除[文件名]为【"+zltxwj.getFwjmc()+"】的法规标准库。";
            spcyLogService.addLogs(LogConstant.LOGS_FGBZK,czContent,zltxwj.getId(), SpcyConstant.LOGS_SYS_TYPE_SC,SpcyConstant.LOGS_SYS_TYPE_SC);
        }

        return HttpResult.ok("删除成功");
    }

    @Log(title = "法规标准库-资源库-导入表格excel")
    @ApiOperation(value = "法规标准库-资源库-导入表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true)
    })
    @PostMapping(value = "impZltxwjData")
    public HttpResult<?> impZltxwjData(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_ZLTXWJ_BASIC, fileUpload);
        } catch (Exception e) {
            log.error("法规标准库-资源库-数据出错-{}",e.getMessage());
        }
        StringBuffer msg = new StringBuffer();
        int index = 0;
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (Map map : mapsList) {
                index++;
                boolean flag = true;

                String id = map.get("id").toString();
                if (StringUtils.isBlank(id)){
                    msg.append("第").append(index).append("行，数据ID为空，不能导入");
                    continue;
                }
                SpcyFgbzkBasic zltxwj = spcyFgbzkBasicService.getById(id);
                if (zltxwj == null){
                    msg.append("第").append(index).append("行，数据ID为[").append(id).append("]，数据不存在，无法导入");
                    continue;
                }else {
                    String forder = map.get("forder").toString();
                    String fwjmc = map.get("fwjmc").toString();
//                    String fwjbh = map.get("fwjbh").toString();
//                    String fskbb = map.get("fskbb").toString();
                    String fxgcs = map.get("fxgcs").toString();
                    String fssrq = map.get("fssrq").toString();
                    String fscrq = map.get("fscrq").toString();

                    zltxwj.setFwjmc(fwjmc);
                    zltxwj.setFwjbh((String)map.get("fwjbh"));
                    zltxwj.setFskbb((String)map.get("fskbb"));

                    if (StringUtils.isNotBlank(forder)) {
                        zltxwj.setForder(Integer.valueOf(forder));
                    }else {
                        zltxwj.setForder(index);
                    }
                    if (StringUtils.isNotBlank(fxgcs)) {
                        zltxwj.setFxgcs(fxgcs);
                    }
                    if (DateConversionUtils.isValidDateStringYmd(fssrq)) {
                        zltxwj.setFssrq(DateConversionUtils.convertStringToDateYmd(fssrq));
                    }else {
                        zltxwj.setFssrq(new Date());
                    }
                    if (DateConversionUtils.isValidDateStringYmd(fscrq)) {
                        zltxwj.setFscrq(DateConversionUtils.convertStringToDateYmd(fscrq));
                    }else {
                        zltxwj.setFscrq(new Date());
                    }

                    flag = spcyFgbzkBasicService.updateById(zltxwj);
                }

                if (flag) {
                    String operContent = "新增导入法规标准库信息：";

                    // 将map里面的属性和值转String
                    Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(zltxwj);
                    operContent += LogUtils.MapToStringMethod(beanMap);
                    spcyLogService.addLogs(LogConstant.LOGS_FGBZK, operContent, id, SpcyConstant.LOGS_SYS_TYPE_XZ, SpcyConstant.LOGS_SYS_TYPE_XZ);
                }
            }
        }
        fileUpload.delete();

        if (StringUtils.isNotBlank(msg)){
            log.error("导入法规标准库-资源库：{}",msg);
            return HttpResult.error(msg.toString());
        }
        return HttpResult.ok("导入成功");
    }

    @Log(title = "法规标准库-盖章失效")
    @ApiOperation(value = "法规标准库-盖章失效")
    @PostMapping(value = "zltxwjGzSx")
    public HttpResult zltxwjGzSx(@RequestBody ParamsBo paramsBo){
        List<SpcyFgbzkBasic> list = spcyFgbzkBasicService.listByIds(StringPatternUtils.getListByIds(paramsBo.getIds()));
        for (int i = 0; i < list.size(); i++) {
            fgbzkBusService.zltxwjGzByZdlx(true, list.get(i));
        }

        return HttpResult.ok("盖章成功");
    }

    @Log(title = "法规标准库-盖章受控")
    @ApiOperation(value = "法规标准库-盖章受控")
    @PostMapping(value = "zltxwjGzSk")
    public HttpResult zltxwjGzSk(@RequestBody ParamsBo paramsBo){
        List<SpcyFgbzkBasic> list = spcyFgbzkBasicService.listByIds(StringPatternUtils.getListByIds(paramsBo.getIds()));
        for (int i = 0; i < list.size(); i++) {
            fgbzkBusService.zltxwjGzByZdlx(false, list.get(i));
        }

        return HttpResult.ok("盖章成功");
    }

    @Log(title = "法规标准库-设置可以下载")
    @ApiOperation(value = "法规标准库-设置可以下载")
    @PostMapping(value = "setYxxz")
    public HttpResult setYxxz(@RequestBody ParamsBo paramsBo){
        if (StringUtils.isBlank(paramsBo.getIds())){
            return HttpResult.error("参数为空！");
        }
        LambdaUpdateWrapper<SpcyFgbzkBasic> updateWrapper= new LambdaUpdateWrapper<>();
        updateWrapper.in(SpcyFgbzkBasic::getId, StringPatternUtils.getListByIds(paramsBo.getIds()));

        SpcyFgbzkBasic updateBean = new SpcyFgbzkBasic();
        updateBean.setFsfyxxz(0);
        spcyFgbzkBasicService.update(updateBean, updateWrapper);

        return HttpResult.ok("保存成功");
    }

    @Log(title = "法规标准库-设置不可以下载")
    @ApiOperation(value = "法规标准库-设置不可以下载")
    @PostMapping(value = "setNotYxxz")
    public HttpResult setNotYxxz(@RequestBody ParamsBo paramsBo){
        if (StringUtils.isBlank(paramsBo.getIds())){
            return HttpResult.error("参数为空！");
        }

        LambdaUpdateWrapper<SpcyFgbzkBasic> updateWrapper= new LambdaUpdateWrapper<>();
        updateWrapper.in(SpcyFgbzkBasic::getId, StringPatternUtils.getListByIds(paramsBo.getIds()));

        SpcyFgbzkBasic updateBean = new SpcyFgbzkBasic();
        updateBean.setFsfyxxz(1);
        spcyFgbzkBasicService.update(updateBean, updateWrapper);

        return HttpResult.ok("保存成功");
    }


    /** 初始化-将所有的体系文件转为pdf */
    @GetMapping(value = "initBasicWordConvertPdf")
    public HttpResult initBasicWordConvertPdf(){
        List<SpcyFgbzkBasic> list = spcyFgbzkBasicService.list();
        for (int i = 0; i < list.size(); i++) {
            fgbzkBusService.zltxwjToPdf(list.get(i), false); // 生成pdf版文件
        }

        return HttpResult.ok();
    }

    /** 初始化-将所有的体系文件转为pdf并盖章受控 */
    @GetMapping(value = "initBasicWordConvertPdfGZsk")
    public HttpResult initBasicWordConvertPdfGZsk(){
        List<SpcyFgbzkBasic> list = spcyFgbzkBasicService.list();
        for (int i = 0; i < list.size(); i++) {
            fgbzkBusService.zltxwjGzByZdlx(false, list.get(i));
        }

        return HttpResult.ok();
    }

    /** 初始化-将所有的体系文件转为pdf并盖章失效 */
    @GetMapping(value = "initBasicWordConvertPdfGZsx")
    public HttpResult initBasicWordConvertPdfGZsx(){
        List<SpcyFgbzkBasic> list = spcyFgbzkBasicService.list();
        for (int i = 0; i < list.size(); i++) {
            fgbzkBusService.zltxwjGzByZdlx(true, list.get(i));
        }

        return HttpResult.ok();
    }

    /** 初始化-将所有的体系文件pdf清空 */
    @GetMapping(value = "emptyBasicWordConvertPdf")
    public HttpResult emptyBasicWordConvertPdf(){
        List<SpcyFgbzkBasic> list = spcyFgbzkBasicService.list(new LambdaQueryWrapper<SpcyFgbzkBasic>()
                .isNotNull(SpcyFgbzkBasic::getFpdfurl));
        for (int i = 0; i < list.size(); i++) {
            if (StringUtils.isNotBlank(list.get(i).getFpdfurl())){
                localFileUploadUtils.deleteLocalFileUrlByZltxwj(list.get(i).getFpdfurl());

                LambdaUpdateWrapper<SpcyFgbzkBasic> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(SpcyFgbzkBasic::getId, list.get(i).getId());

                SpcyFgbzkBasic updateBean = new SpcyFgbzkBasic();
                updateBean.setFpdfurl("");
                spcyFgbzkBasicService.update(updateBean, updateWrapper);
            }
        }

        return HttpResult.ok();
    }

    /*@Log(title = "读取文件夹里面的文件")
    @ApiOperation(value = "读取文件夹里面的文件")*/
    @PostMapping(value = "initZltxwjDirFile")
    public HttpResult<?> initZltxwjDirFile(@RequestBody HashMap<String,String> map){
        String url = map.get("url");
        File dir = new File(url);
        this.listAllFile(url,dir,0,"","");

        return HttpResult.ok("初始化文件成功");
    }

    /**
     * 获取目录下的所有文件
     * @param f
     */
    public void listAllFile(String baseUrl,File f, int count, String wjml, String xdlj) {
        File[] files = f.listFiles();
        String fl = wjml; // 分类
        String absUrl = xdlj; // 相对路径
        String cflj = "/" + SpcyConstant.FGBZK_File_Base_Url; // 存放基础路径

        for (File file : files) {

            // 文件夹
            if (file.isDirectory()) {
                fl += file.getName() + ",";
                absUrl += "/" + file.getName();

                this.listAllFile(baseUrl,file,count,fl,absUrl);
            }

            // 不是文件夹
            if (!file.isDirectory()) {

                count++;
                SpcyFgbzkBasic zltxwj = new SpcyFgbzkBasic();
                zltxwj.setId(GetUuIdUtils.ReplaceUuId());
                zltxwj.setForder(count);

                /**
                 * 获取最后一个分类
                 */
                String[] split = fl.split(",");
                String ftype = split[split.length-1];
                zltxwj.setFtype(ftype);

                String fileName = file.getName();
                int firstChineseIndex = CharacterEncodingConvertUtils.firstChineseIndex(fileName);
                zltxwj.setFwjbh(fileName.substring(0,firstChineseIndex));
                zltxwj.setFwjmc(Util.getWjmcNoHz(fileName));
                zltxwj.setFwjlx(Util.getWjHz(file.getName()));

                int length = baseUrl.length();
                String absolutePath = file.getAbsolutePath();
                zltxwj.setFwjlj(cflj+absolutePath.substring(length,absolutePath.length()));
                zltxwj.setFssrq(new Date());
                zltxwj.setFscrq(new Date());

                spcyFgbzkBasicService.save(zltxwj);

            }
        }

    }

    @Log(title = "下载法规标准库-资源库-导入模板")
    @ApiOperation(value = "下载法规标准库-资源库-导入模板")
    @GetMapping("/downZltxwjTemplate")
    public void downZltxwjTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("zltxwjImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_ZLTXWJ_BASIC, out);
        } catch (Exception e) {
            log.error("下载法规标准库-资源库-导入模板错误-{}",e.getMessage());
        }
    }

    @Log(title = "导出法规标准库-资源库数据-表格excel")
    @ApiOperation(value = "导出法规标准库-资源库数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "法规标准库id字符逗号分割",dataType = "String")
    })
    @GetMapping("/exportZltxwjData")
    public void exportZltxwjData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                 SpcyFgbzkBasic SpcyFgbzkBasic,
                                 HttpServletResponse response){
        try {
            String name = "exportZltxwjData";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcyFgbzkBasic> zltxwjList = spcyFgbzkBasicService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(zltxwjList)){
                    for (SpcyFgbzkBasic e : zltxwjList){
                        list.add(e);
                    }
                }
            }else {
                /*LambdaQueryWrapper<SpcyFgbzkBasic> wrapper = new LambdaQueryWrapper<>();
                wrapper.like(StringUtils.isNotBlank(SpcyFgbzkBasic.getFskbb()),SpcyFgbzkBasic::getFskbb,SpcyFgbzkBasic.getFskbb());
                wrapper.like(StringUtils.isNotBlank(SpcyFgbzkBasic.getFtype()),SpcyFgbzkBasic::getFtype,SpcyFgbzkBasic.getFtype());
                wrapper.like(StringUtils.isNotBlank(SpcyFgbzkBasic.getFwjbh()),SpcyFgbzkBasic::getFwjbh,SpcyFgbzkBasic.getFwjbh());
                wrapper.like(StringUtils.isNotBlank(SpcyFgbzkBasic.getFwjmc()),SpcyFgbzkBasic::getFwjmc,SpcyFgbzkBasic.getFwjmc());
                wrapper.like(StringUtils.isNotBlank(SpcyFgbzkBasic.getFzt()),SpcyFgbzkBasic::getFzt,SpcyFgbzkBasic.getFzt());
                wrapper.orderByAsc(SpcyFgbzkBasic::getForder);
                wrapper.orderByAsc(SpcyFgbzkBasic::getCreateTime);
                wrapper.orderByAsc(SpcyFgbzkBasic::getFscrq);
                List<SpcyFgbzkBasic> zltxwjList = spcyFgbzkBasicService.list(wrapper);*/
                List<SpcyFgbzkBasic> zltxwjList = spcyFgbzkBasicMapper.selectZltxwjList(SpcyFgbzkBasic);
                // 条件导出
                if (CollectionUtils.isNotEmpty(zltxwjList)){
                    for (SpcyFgbzkBasic e : zltxwjList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_ZLTXWJ_BASIC,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出法规标准库-资源库数据出错-{}",e.getMessage());
        }
    }
}
